﻿<?php
class AfterworkModel extends Model{

	public $id;
	public $date;
	public $place;
	public $description;
	public $id_login;
	public $selected;
	
	public function __construct()
	{
	}
	
	public static function GetWeek()
	{
		$db = new DbContext();
		$connec = $db->getConnection();
		
		$q =   "SELECT a.*,COUNT(s.id)
				FROM afterwork a 
				LEFT JOIN subscription s 
				ON s.afterwork_id = a.id AND s.vote = 'Yes'
				WHERE WEEK(a.date) = WEEK(NOW())
				AND TO_DAYS(a.date) >= TO_DAYS(NOW())
				GROUP BY a.id
				ORDER BY COUNT(s.id) DESC";
		
		$q=$connec->query($q);
		$q->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'AfterworkModel'); 
		$afterwork = $q->fetchAll();
		
		return $afterwork;
	}
	
	public static function GetNextWeek()
	{
		$db = new DbContext();
		$connec = $db->getConnection();
		
		$q = "SELECT * FROM afterwork WHERE WEEK(date) = WEEK(NOW()) + 1";
		
		$q=$connec->query($q);	
		$q->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'AfterworkModel'); 	
		$afterwork = $q->fetchAll();
		
		return $afterwork;
	}
	
	public function GetProposer()
	{
		$db = new DbContext();
		$connec = $db->getConnection();
		
		$q = "SELECT * FROM login WHERE id = :id_login";
		
		$q=$connec->prepare($q);		
		$q->execute(array( 'id_login' => $this->id_login ));
		$q->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'LoginModel'); 	
		$login = $q->fetch();
		
		return $login;
	}
	
	public function GetAnsweredSubscribers($answer = null)
	{
		$db = new DbContext();
		$connec = $db->getConnection();
		
		$q = "SELECT * FROM subscription s WHERE s.afterwork_id = :af_id";
		if ($answer == null)
			$q.= " AND s.answer IS NOT NULL";
		else
			$q.= " AND s.answer = '".$answer."'";
			
		$q.= " ORDER BY s.answer DESC, s.vote DESC";
		$q=$connec->prepare($q);		
		$q->execute(array( 'af_id' => $this->id ));
		$q->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'SubscriptionModel');
		
		return $q->fetchAll();
	}
	
	public function GetAllSubscribers()
	{
		$db = new DbContext();
		$connec = $db->getConnection();
		
		$q = "SELECT * FROM subscription s WHERE s.afterwork_id = :af_id ORDER BY s.answer DESC, s.vote DESC";
		
		$q=$connec->prepare($q);		
		$q->execute(array( 'af_id' => $this->id ));
		$q->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'SubscriptionModel');
		
		return $q->fetchAll();
	}
}
?>
